package com.alex.tkmybatis.service.impl;

import com.alex.tkmybatis.common.ExampleWrapper;
import com.alex.tkmybatis.common.ExampleWrapperFactory;
import com.alex.tkmybatis.entity.User;
import com.alex.tkmybatis.mapper.UserMapper;
import com.alex.tkmybatis.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void addUser(User user) {
        userMapper.insert(user);
    }

    /**
     * 按条件删除
     * @param user
     */
    @Override
    public void deleteUser(User user) {
        ExampleWrapper<User> wrapper = ExampleWrapperFactory.create(User.class);
            wrapper.andEqualTo(User::getUsername, user.getUsername());
        userMapper.deleteByExample(wrapper);
    }

    /**
     * mybatis-plus lambda 条件式 按条件查询
     * @param user
     * @return
     */
    @Override
    public List<User> queryUsersByPlus(User user) {
        ExampleWrapper<User> wrapper = ExampleWrapperFactory.create(User.class);
        wrapper.andEqualTo(User::getUsername, user.getUsername());//lambda表达式
        return userMapper.selectByExample(wrapper);
    }

    /**
     * tk-mybatis原来的形式 按条件查询
     * @param user
     * @return
     */
    @Override
    public List<User> queryUsers(User user) {
        Example example = new Example(User.class);
        example.setOrderByClause("create_time DESC");
        example.createCriteria().andEqualTo("username", user.getUsername());
        return userMapper.selectByExample(example);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateByPrimaryKey(user);
    }
}
